<template>
  <div class="app-container">
    <div class="component-1">
      <div class="campus-bus-reservation-system-reservation">个人资料</div>
    </div>
    <div class="background">
      <div class="info-item">
        <div>姓名:</div>
        <div>{{ form.realname || "未填写" }}</div>
      </div>
      <div class="info-item">
        <div>工号:</div>
        <div>{{ form.teacherCode || "未填写" }}</div>
      </div>
      <div class="info-item">
        <div>手机号：</div>
        <div>{{ form.phone || "未填写" }}</div>
      </div>
      <div class="info-item">
        <div>学院:</div>
        <div>{{ form.collegeName || "未填写" }}</div>
      </div>
      <div class="info-item">
        <div>
          <el-button
            type="primary"
            size="small"
            @click="handleUpdateInfo"
            :loading="loading"
            :disabled="loading"
            >修改个人信息</el-button
          >
          <!-- <el-button type="primary" size="small" :loading="loading" :disabled="loading"
            >修改密码</el-button
          > -->
        </div>
      </div>
    </div>
  </div>

  <!-- 新增教师弹窗 -->
  <el-dialog v-model="dialogVisible" title="新增教师" width="80%" append-to-body :close-on-click-modal="false" :show-close="false">
    <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
      <el-form-item label="教师姓名" prop="realname">
        <el-input v-model="addForm.realname" placeholder="请输入教师姓名" />
      </el-form-item>
      <el-form-item label="教师工号" prop="teacherCode">
        <el-input v-model="addForm.teacherCode" placeholder="请输入教师工号" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="addForm.phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="学院" prop="collegeName">
        <el-input v-model="addForm.collegeName" placeholder="请输入学院" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
        <!-- <el-button @click="cancelAddForm">取 消</el-button> -->
      </div>
    </template>
  </el-dialog>
  <!-- 修改个人信息弹窗 -->
  <el-dialog
    v-model="dialogVisibleUpdate"
    title="修改个人信息"
    width="80%"
    append-to-body
  >
    <el-form
      ref="updateFormRef"
      :model="updateForm"
      :rules="addRules"
      label-width="100px"
    >
      <el-form-item label="教师姓名" prop="realname">
        <el-input v-model="updateForm.realname" placeholder="请输入教师姓名" disabled />
      </el-form-item>
      <el-form-item label="教师工号" prop="teacherCode">
        <el-input v-model="updateForm.teacherCode" placeholder="请输入教师工号" disabled />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="updateForm.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="学院" prop="collegeName">
        <el-input v-model="updateForm.collegeName" placeholder="请输入学院" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitUpdateForm">确 定</el-button>
        <el-button @click="cancelUpdateForm">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getDetail, addTeacher, updateTeacher, listTeacher } from "@/api/infomanagement/teacher";
import useUserStore from "@/store/modules/user";
import { useTeacherStore } from '@/store/modules/teacher';
const userStore = useUserStore();
const loading = ref(false);
const dialogVisible = ref(false); // 控制新增教师弹窗的显示
const dialogVisibleUpdate = ref(false); // 控制修改个人信息弹窗的显示

// 表单验证规则（新增/修改共用）
const addRules = reactive({
  realname: [{ required: true, message: "请输入教师姓名", trigger: "blur" }],
  teacherCode: [
    { required: true, message: "请输入教师工号", trigger: "blur" },
    {
      validator: async (rule, value, callback) => {
        // 新增时检查工号唯一性
        if (value && dialogVisible.value) {
          try {
            // 调用列表接口查询工号是否存在
            const res = await listTeacher({ teacherCode: value });
            if (res.code === 200 && res.rows && res.rows.length > 0) {
              callback(new Error('该工号已存在，请输入其他工号'));
            } else {
              callback();
            }
          } catch (error) {
            callback(new Error('工号验证失败，请稍后重试'));
          }
        } else {
          // 修改时工号不可编辑，不需要校验
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号码", trigger: "blur" },
  ],
  collegeName: [{ required: true, message: "请输入学院名称", trigger: "blur" }],
});

// 新增教师表单数据
const addFormRef = ref(null);
const addForm = reactive({
  realname: "",
  phone: "",
  teacherCode: "",
  collegeName: "",
  loginId: parseInt(userStore.id), // 关联当前用户ID
});

// 修改个人信息表单数据
const updateFormRef = ref(null);
const updateForm = reactive({
  userId: "",
  realname: "",
  teacherCode: "",
  phone: "",
  collegeName: "",
  loginId: parseInt(userStore.id),
});

const teacherStore = useTeacherStore();
const form = reactive({
  loginId: parseInt(userStore.id),
  userId: '',
  realname: '',
  teacherCode: '',
  phone: '',
  collegeName: '',
});

// 提交新增教师表单
const submitAddForm = async () => {
  if (!addFormRef.value) return;
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await addTeacher(addForm);
        ElMessage.success("新增教师成功");
        dialogVisible.value = false;
        resetAddForm();
        fetchTeacherDetail(); // 刷新教师详情
      } catch (error) {
        ElMessage.error("新增教师失败");
      }
    }
  });
};

// 取消新增教师表单
const cancelAddForm = () => {
  dialogVisible.value = false;
  resetAddForm();
};

// 重置新增教师表单
const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  Object.assign(addForm, {
    userId: form.userId,
    realname: "",
    phone: "",
    teacherCode: "",
    collegeName: "",
    loginId: parseInt(userStore.id),
  });
};

// 获取教师详情
const fetchTeacherDetail = async () => {
  loading.value = true;
  try {
    
    const res = await getDetail(parseInt(userStore.id));
    if (res.data == null) {
      dialogVisible.value = true;
      return;
    }
    form.userId = res.data.userId;
    form.realname = res.data.realname;
    form.teacherCode = res.data.teacherCode;
    form.phone = res.data.phone;
    form.collegeName = res.data.collegeName;
    form.loginId = res.data.loginId;
    teacherStore.setTeacherInfo(res.data);
  } catch (error) {
    ElMessage.error("获取个人信息失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchTeacherDetail();
});

// 修改个人信息
const handleUpdateInfo = () => {
  // 回显当前个人信息到修改表单
  Object.assign(updateForm, {
    userId: form.userId,
    realname: form.realname,
    teacherCode: form.teacherCode,
    phone: form.phone,
    collegeName: form.collegeName,
    loginId: form.loginId,
  });
  dialogVisibleUpdate.value = true; // 打开修改弹窗
};

// 提交修改个人信息表单
const submitUpdateForm = async () => {
  if (!updateFormRef.value) return;
  await updateFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await updateTeacher(updateForm);
        ElMessage.success("修改个人信息成功");
        dialogVisibleUpdate.value = false;
        // 存储更新后的个人信息到store
        teacherStore.setTeacherInfo({
          loginId: form.loginId,
          userId: form.userId,
          realname: form.realname,
          teacherCode: form.teacherCode,
          phone: form.phone,
          collegeName: form.collegeName,
        });
       // 刷新个人信息
      } catch (error) {
        ElMessage.error("修改个人信息失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 取消修改个人信息表单
const cancelUpdateForm = () => {
  dialogVisibleUpdate.value = false;
  if (updateFormRef.value) {
    updateFormRef.value.resetFields();
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px 0 30px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.component-1 {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  border-radius: 6px; /* 从小导航的borderRadius推断，整个组件可能也有圆角 */
}

.campus-bus-reservation-system-reservation {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 70px;
  font-size: 20px;
  line-height: 1.2102272727272727em;
  color: #ffffff; /* 假设文本颜色为黑色，Figma数据中未明确给出 */
}
.background {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #ffffff;
  height: calc(85vh - 70px); /* 占满屏幕底部，直到导航栏的位置 */
  padding-bottom: env(safe-area-inset-bottom); /* 适配底部安全区域 */
}
.info-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 50px;
  font-size: 16px;
  line-height: 1.2102272245619032em;
  /* 两侧对齐 */
  justify-content: space-between;
  padding: 0 20px;
  color: #000000; /* 假设文本颜色为黑色，Figma数据中未明确给出 */
}
</style>
